import { NavLink, Outlet, useNavigate, useLocation } from "react-router-dom";
import React, { useEffect, useContext, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faMagnifyingGlass, faBars, faTimes } from "@fortawesome/free-solid-svg-icons"; // 引入 faBars 和 faTimes
import "../css/headerStyles.css";
import { AppState } from "../App";

const Header = ({ address }) => {
  const App = useContext(AppState);
  const navigate = useNavigate();
  const [isAdmin, setIsAdmin] = useState(false);
  const location = useLocation();
  const [searchKeyword, setSearchKeyword] = useState("");
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); // 移动菜单状态

  useEffect(() => {
    const fetchManagerAddress = async () => {
      try {
        const managerAddress = await App.Foundationcontract.manager();
        if (managerAddress.toLowerCase() === address.toLowerCase()) {
          setIsAdmin(true);
        }
      } catch (error) {
        console.error("获取管理员地址时出错:", error);
      }
    };
    fetchManagerAddress();
  }, [address, App.Foundationcontract]);

  useEffect(() => {
    const handleRouteChange = () => {
      const searchParams = new URLSearchParams(location.search);
      const pathname = location.pathname;
      if (
        (pathname === "/header/main" ||
          pathname === "/header/songwarm" ||
          pathname === "/header/forus" ||
          pathname === "/header/profile" ||
          pathname === "/header/manager") &&
        !searchParams.has("keyword")
      ) {
        setSearchKeyword("");
      }
    };
    handleRouteChange();
  }, [location]);

  const handleLogout = async () => {
    try {
      const res = await window.ethereum.request({
        method: "wallet_revokePermissions",
        params: [
          {
            eth_accounts: {},
          },
        ],
      });
      console.log("连接已断开", res);
      navigate("/");
    } catch (error) {
      console.error("撤销权限时出错:", error);
    }
  };

  const handleSearch = () => {
    if (searchKeyword === "") {
      alert("请输入搜索内容");
    } else {
      navigate(`/header/search?keyword=${encodeURIComponent(searchKeyword)}`);
    }
  };

  const handleKeyPress = (event) => {
    if (event.key === "Enter") {
      handleSearch();
    }
  };

  const toggleMobileMenu = () => {
    setIsMobileMenuOpen(!isMobileMenuOpen);
  };

  return (
    <>
      <header id="header" className="headerStyle">
        <div className="a">
          <div className="left">

            <img src="/images/logo1.png" className="headerLogo" alt="logo" />
            <div className="left-item">
              SongWarm颂暖
            </div>
          </div>
          <div className="searchBox">
            <input
              type="text"
              placeholder="搜索..."
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              onKeyPress={handleKeyPress}
              className="searchInput"
            />
            <button className="searchButton" onClick={handleSearch}>
              <FontAwesomeIcon icon={faMagnifyingGlass} />
            </button>
          </div>

          <button className="mobile-menu-icon" onClick={toggleMobileMenu}>
            <FontAwesomeIcon icon={isMobileMenuOpen ? faTimes : faBars} />
          </button>

          <nav className={`right ${isMobileMenuOpen ? "open" : ""}`}>
            <span className="right-item">
              <NavLink to="/header/main" className="linkStyle" activeClassName="activeLink">
                首页
              </NavLink>
            </span>
            <span className="right-item">
              <div className="dropdown">
                <button className="dropbtn linkStyle">
                  <NavLink
                    to={`/header/songwarm?tittle=${encodeURIComponent("")}`}
                    className="linkStyle"
                    activeClassName="activeLink"
                  >
                    送暖
                  </NavLink>
                </button>
                <div className="dropdown-content">
                  <NavLink
                    to={`/header/songwarm?tittle=${encodeURIComponent(
                      "教育资助"
                    )}`}
                    className="linkStyle"
                  >
                    教育资助
                  </NavLink>
                  <NavLink
                    to={`/header/songwarm?tittle=${encodeURIComponent(
                      "慈善救助"
                    )}`}
                    className="linkStyle"
                  >
                    慈善救助
                  </NavLink>
                  <NavLink
                    to={`/header/songwarm?tittle=${encodeURIComponent(
                      "环境保护"
                    )}`}
                    className="linkStyle"
                  >
                    环境保护
                  </NavLink>
                  <NavLink
                    to={`/header/songwarm?tittle=${encodeURIComponent(
                      "社会福利"
                    )}`}
                    className="linkStyle"
                  >
                    社会福利
                  </NavLink>
                  <NavLink
                    to={`/header/songwarm?tittle=${encodeURIComponent(
                      "文化艺术"
                    )}`}
                    className="linkStyle"
                  >
                    文化艺术
                  </NavLink>
                </div>
              </div>
            </span>

            <span className="right-item">
              <NavLink to="/header/forus" className="linkStyle" activeClassName="activeLink">
                为我们筹款
              </NavLink>
            </span>
            <span className="right-item">
              <NavLink to="/header/profile" className="linkStyle" activeClassName="activeLink">
                个人信息
              </NavLink>
            </span>
            {isAdmin && (
              <span className="right-item">
                <NavLink to="/header/manager" className="linkStyle" activeClassName="activeLink">
                  管理员
                </NavLink>
              </span>
            )}
            <span className="right-item">
              <button className="linkStyle" onClick={handleLogout}>
                退出
              </button>
            </span>
          </nav>
        </div>
      </header>

      <div>
        <Outlet context={{ address }} />
      </div>
    </>
  );
};

export default Header;
